package com.icehelper.hades.base.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.icehelper.hades.base.log.HadesLogger;
import com.icehelper.hades.base.util.Inspections;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/** web相关一些工具方法。 */
public class WebContext {

  private static final HadesLogger log = HadesLogger.create(WebContext.class);

  public static HttpServletRequest getHttpRequest() {
    return getRequestAttributes().getRequest();
  }

  public static HttpServletResponse getHttpResponse() {
    return getRequestAttributes().getResponse();
  }

  public static ServletRequestAttributes getRequestAttributes() {
    return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  }

  public static <T> Pagination<T> buildPage() {
    HttpServletRequest request = getHttpRequest();
    String sPageNo = request.getParameter("pageNo");
    int pageNo = 1;
    if ( Inspections.isDigit(sPageNo)) {
      try {
        pageNo = Integer.parseInt(sPageNo);
      } catch (NumberFormatException e) {
        log.warn("parse pageNo failed. use default value:{}, pageNo:{}", pageNo, sPageNo, e);
      }
    }
    String sPageSize = request.getParameter("pageSize");
    int pageSize = 10;
    if ( Inspections.isDigit(sPageNo)) {
      try {
        pageSize = Integer.parseInt(sPageSize);
      } catch (NumberFormatException e) {
        log.warn("parse pageSize failed. use default value:{}, pageSize:{}", pageSize, sPageSize, e);
      }
    }
    if (pageNo < 1) {
      pageNo = 1;
    }
    if (pageSize < 1) {
      pageSize = 10;
    }
    return new Pagination<>(pageNo, pageSize);
  }
}
